package com.feeyo.groundservice.easyphotoplus.use

import android.Manifest
import android.content.Context
import android.content.Intent
import android.provider.MediaStore
import android.widget.ImageView
import androidx.activity.result.ActivityResultLauncher
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.feeyo.groundservice.easyphotoplus.R
import com.feeyo.groundservice.easyphotoplus.basic.PictureSelector
import com.feeyo.groundservice.easyphotoplus.config.SelectMimeType
import com.feeyo.groundservice.easyphotoplus.entity.LocalMedia
import com.feeyo.groundservice.easyphotoplus.interfaces.OnCameraInterceptListener
import com.feeyo.groundservice.easyphotoplus.interfaces.OnRecordAudioInterceptListener
import com.feeyo.groundservice.easyphotoplus.interfaces.OnResultCallbackListener
import com.feeyo.groundservice.easyphotoplus.permissions.PermissionChecker
import com.feeyo.groundservice.easyphotoplus.permissions.PermissionResultCallback
import com.feeyo.groundservice.easyphotoplus.style.BottomNavBarStyle
import com.feeyo.groundservice.easyphotoplus.style.PictureSelectorStyle
import com.feeyo.groundservice.easyphotoplus.style.SelectMainStyle
import com.feeyo.groundservice.easyphotoplus.style.TitleBarStyle
import com.feeyo.groundservice.easyphotoplus.utils.DensityUtil
import com.feeyo.groundservice.easyphotoplus.utils.ToastUtils
import com.luck.lib.camerax.CameraImageEngine
import com.luck.lib.camerax.SimpleCameraX

/**
 *作者：70893 on 2025-04-05
 *描述：
 */

object EasyPhotoPlusUtil {

    /**打开文件管理器
     *
     * 监听onActivityResult
     * **/

    fun openFileManager(launcher: ActivityResultLauncher<Intent>) {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "*/*"
        intent.addCategory(Intent.CATEGORY_OPENABLE)

        launcher.launch(intent)
    }

    /**直接拍照,视频 ,录音
     *
     *
     * @param type ofImage ofVideo ofAudio
     * @param isCompress 是否压缩
     * @param isCrop 是否裁剪
     * @param callback 回调
     *
     * 最好提前请求权限：
     * 1.拍照：Manifest.permission.CAMERA
     * 2.视频：Manifest.permission.CAMERA
     * 3.录音：Manifest.permission.RECORD_AUDIO
     * **/

    fun openCamera(
        context: Context,
        type: Int,
        isCompress: Boolean = false,
        isCrop: Boolean = false,
        callback: OnResultCallbackListener<LocalMedia>
    ) {
        PictureSelector.create(context)
            .openCamera(type)
            .let {
                if (type == SelectMimeType.ofAudio()) {
                    it.setRecordAudioInterceptListener(getRecordAudioListener)
                }
                //照片才能压缩 裁剪
                if (type == SelectMimeType.ofImage()) {
                    if (isCompress)
                        it.setCompressEngine(ImageFileCompressEngine())

                    if (isCrop)
                        it.setCropEngine(ImageFileCropEngine())
                }
                it
            }
            .forResult(callback)
    }

    /**自定义拍照 视频
     *
     * @param type ofImage ofVideo ofAudio
     * @param isCompress 是否压缩
     * @param isCrop 是否裁剪
     * @param callback 回调
     * **/
    fun openCustomCamera(
        context: Context,
        type: Int,
        isCompress: Boolean = false,
        isCrop: Boolean = false,
        callback: OnResultCallbackListener<LocalMedia>
    ) {
        PictureSelector.create(context)
            .openCamera(type)
            .let {
                //照片才能压缩 裁剪
                if (type == SelectMimeType.ofImage()) {
                    if (isCompress)
                        it.setCompressEngine(ImageFileCompressEngine())

                    if (isCrop)
                        it.setCropEngine(ImageFileCropEngine())
                }
                it
            }
            .setCameraInterceptListener(getCustomCameraListener)
            .forResult(callback)
    }

    /**相册+拍照 视频 录音
     *
     * @param type ofImage ofVideo ofAudio
     * @param isCompress 是否压缩
     * @param isCrop 是否裁剪
     * @param isGif 是否gif
     * @param selectCount 选择数量
     * @param callback 回调
     *
     * **/
    fun openAlbum(
        context: Context,
        type: Int,
        isDisplayCamera: Boolean = false,
        isCompress: Boolean = false,
        isCrop: Boolean = false,
        isGif:Boolean = false,
        selectCount: Int = 10,
        callback: OnResultCallbackListener<LocalMedia>
    ) {
        PictureSelector.create(context)
            .openGallery(type)
            .setSelectorUIStyle(getDefaultUIStyle(context))
            .setImageEngine(GlideEngine.createGlideEngine())
            .setMaxSelectNum(selectCount)
            .isMaxSelectEnabledMask(true)
            .let {
                if (type == SelectMimeType.ofAudio()) {
                    it.setRecordAudioInterceptListener(getRecordAudioListener)
                }
                //照片才能压缩 裁剪
                if (type == SelectMimeType.ofImage()) {
                    if (isCompress)
                        it.setCompressEngine(ImageFileCompressEngine())

                    if (isCrop)
                        it.setCropEngine(ImageFileCropEngine())
                }
                it
            }
            .isDisplayCamera(isDisplayCamera)//是否显示拍摄按钮
            .isDisplayTimeAxis(true)
            .isGif(isGif)
            .forResult(callback)
    }

    private val getRecordAudioListener = OnRecordAudioInterceptListener { fragment, requestCode ->
        val recordAudio = arrayOf(Manifest.permission.RECORD_AUDIO)
        if (PermissionChecker.isCheckSelfPermission(fragment.requireContext(), recordAudio)) {
            startRecordSoundAction(fragment, requestCode)
        } else {
            PermissionChecker.getInstance()
                .requestPermissions(fragment, recordAudio, object : PermissionResultCallback {
                    override fun onGranted() {
                        startRecordSoundAction(fragment, requestCode)
                    }

                    override fun onDenied() {
                        val tips = "缺少麦克风权限\n可能会导致录视频无法采集声音"
                        ToastUtils.showToast(fragment.requireContext(), tips)
                    }
                })
        }
    }

    /**
     * 启动录音意图
     *
     * @param fragment
     * @param requestCode
     */
    private fun startRecordSoundAction(fragment: Fragment, requestCode: Int) {
        val recordAudioIntent = Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION)
        if (recordAudioIntent.resolveActivity(fragment.requireActivity().packageManager) != null) {
            fragment.startActivityForResult(recordAudioIntent, requestCode)
        } else {
            ToastUtils.showToast(
                fragment.getContext(),
                "The system is missing a recording component"
            )
        }
    }


    private val getCustomCameraListener =
        OnCameraInterceptListener { fragment, cameraMode, requestCode ->
            val camera: SimpleCameraX = SimpleCameraX.of()
            camera.isAutoRotation(true)
            camera.setCameraMode(cameraMode)
            camera.setVideoFrameRate(25)
            camera.setVideoBitRate(3 * 1024 * 1024)
            camera.isDisplayRecordChangeTime(true)
            camera.isManualFocusCameraPreview(true)

            camera.setImageEngine(object : CameraImageEngine {
                override fun loadImage(context: Context, url: String?, imageView: ImageView) {
                    Glide.with(context).load(url).into(imageView)
                }
            })
            camera.start(fragment.requireActivity(), fragment, requestCode)
        }

    fun getDefaultUIStyle(context: Context) = PictureSelectorStyle().apply {
        // 主体风格
        val numberSelectMainStyle = SelectMainStyle().apply {
            isSelectNumberStyle = true
            isPreviewSelectNumberStyle = false
            isPreviewDisplaySelectGallery = true
            selectBackground = R.drawable.ps_default_num_selector
            previewSelectBackground = R.drawable.ps_preview_checkbox_selector
            selectNormalBackgroundResources = R.drawable.ps_select_complete_normal_bg
            selectNormalTextColor = ContextCompat.getColor(context, R.color.ps_color_53575e)
            setSelectNormalText(R.string.ps_send)
            setAdapterPreviewGalleryBackgroundResource(R.drawable.ps_preview_gallery_bg);
            setAdapterPreviewGalleryItemSize(DensityUtil.dip2px(context, 52f))
            setPreviewSelectText(R.string.ps_select)
            setPreviewSelectTextSize(14)
            setPreviewSelectTextColor(ContextCompat.getColor(context, R.color.ps_color_white))
            setPreviewSelectMarginRight(DensityUtil.dip2px(context, 6f))
            setSelectBackgroundResources(R.drawable.ps_select_complete_bg)
            setSelectText(R.string.ps_send_num)
            setSelectTextColor(ContextCompat.getColor(context, R.color.ps_color_white))
            setMainListBackgroundColor(ContextCompat.getColor(context, R.color.ps_color_black))
            setCompleteSelectRelativeTop(true)
            setPreviewSelectRelativeBottom(true)
            setAdapterItemIncludeEdge(false)
        }
        // 头部TitleBar 风格
        val numberTitleBarStyle = TitleBarStyle().apply {
            isHideCancelButton = true
            isAlbumTitleRelativeLeft = true
            setTitleAlbumBackgroundResource(R.drawable.ps_album_bg)
            setTitleDrawableRightResource(R.drawable.ps_ic_grey_arrow);
            setPreviewTitleLeftBackResource(R.drawable.ps_ic_normal_back)
        }

        // 底部NavBar 风格
        val numberBottomNavBarStyle = BottomNavBarStyle().apply {
            setBottomPreviewNarBarBackgroundColor(
                ContextCompat.getColor(
                    context,
                    R.color.ps_color_half_grey
                )
            );
            setBottomPreviewNormalText(R.string.ps_preview);
            setBottomPreviewNormalTextColor(ContextCompat.getColor(context, R.color.ps_color_9b));
            setBottomPreviewNormalTextSize(16);
            setCompleteCountTips(false);
            setBottomPreviewSelectText(R.string.ps_preview_num);
            setBottomPreviewSelectTextColor(
                ContextCompat.getColor(
                    context,
                    R.color.ps_color_white
                )
            );
        }
        titleBarStyle = numberTitleBarStyle
        bottomBarStyle = numberBottomNavBarStyle
        selectMainStyle = numberSelectMainStyle
    }
}